<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/19
 * Time: 8:42
 */
namespace app\admin\model;

use think\Model;
use think\Db;

class MemberModel extends Model
{
    // 确定链接表名
    protected $name = 'member';

    /**
     * 查询会员数据
     */
    public function getMemberByWhere ($where, $offset, $limit)
    {
        $memberArr = $this->where($where)->where($this->whereCansee())->limit($offset, $limit)->order('id desc')->select();
		 // print_r(Db::table('member')->getLastSql());
        foreach($memberArr as $key=>&$vo){
            $firstRelation = $vo['first_relation'];
			$second_relation = $vo['second_relation'];
			if ($second_relation == 0) {
				$userArr = Db::name('user')->where(['id'=>$firstRelation])->find();
	            $vo['relation'] = $userArr['real_name'];
				$vo['relation_id'] = $firstRelation;
	            $vo['time'] = date('Y-m-d',$vo['entry_time']);
                $vo['time_K'] = date('Y-m-d H:i:s',$vo['entry_time']);
			}else {
				$userArr = Db::name('user')->where(['id'=>$second_relation])->find();
				$vo['relation'] = $userArr['real_name'];
				$vo['relation_id'] = $second_relation;
	            $vo['time'] = date('Y-m-d',$vo['second_time']);
                $vo['time_K'] = date('Y-m-d H:i:s',$vo['second_time']);
			}
        }
        return $memberArr;
    }
	/**
	 * 新的客户数量查询
	 * 客户分享列表
	 */
	 public function getShareMember ($where, $offset, $limit)
     {
         $memberArr = $this->where($where)->limit($offset, $limit)->order('id desc')->select();
         foreach($memberArr as $key=>&$vo){
             $firstRelation = $vo['first_relation'];
 			$second_relation = $vo['second_relation'];
 			if ($second_relation == 0) {
 				$userArr = Db::name('user')->where(['id'=>$firstRelation])->find();
 	            $vo['relation'] = $userArr['real_name'];
 				$vo['relation_id'] = $firstRelation;
 	            $vo['time'] = date('Y-m-d',$vo['entry_time']);
                 $vo['time_K'] = date('Y-m-d H:i:s',$vo['entry_time']);
 			}else {
 				$userArr = Db::name('user')->where(['id'=>$second_relation])->find();
 				$vo['relation'] = $userArr['real_name'];
 				$vo['relation_id'] = $second_relation;
 	            $vo['time'] = date('Y-m-d',$vo['second_time']);
                 $vo['time_K'] = date('Y-m-d H:i:s',$vo['second_time']);
 			}
         }
         return $memberArr;
     }
    /**
     * 根据搜索条件获取所有的会员数量
     * @param $where
     */
    public function getAllMember($where)
    {
        return $this->where($where)->where($this->whereCansee())->count();
		// print_r($this->getLastSql());
    }
	/**
     * 添加客户信息并返回会员id
     * @ $where
     */
	 public function addMember($where){
		 try{
             $memberId = $this->validate('MemberValidate')->insertGetId($where);
             if(empty($memberId)){
                 // 验证失败 输出错误信息
                 return msg(-1, '', $this->getError());
             }else{
                 return $memberId;
             }
         }catch(\Exception $e){
             return msg(-2, '', $e->getMessage());
         }
     }
	 //添加资源客户
	 public function addResMember($param){
		 try{
             $result = $this->validate('MemberValidate')->save($param);
             if(false === $result){
                 // 验证失败 输出错误信息
                 return msg(-1, '', $this->getError());
             }else{

                 return msg(1, url('Member/addResMember'), '添加成功');
             }
         }catch(\Exception $e){
             return msg(-2, '', $e->getMessage());
         }
     }
	/**
	 * 强制释放
	 * @ id
	 */
	 public function release($param){
		 $uid = session('id');
		 $ids = json_decode($param);
         try{
             foreach($ids as $v){
				 $memberA = $this->where('id',$v)->find();
				 if ($memberA['second_relation'] == 0) {
	 				if ($memberA['first_relation'] == $uid) {
	 					return ['code'=>2,'msg'=>'不可释放数据'];
	 				}
	 			}else {
					if ($memberA['second_relation'] == $uid) {
	 					return ['code'=>2,'msg'=>'不可释放数据'];
	 				}
	 			}
				if($memberA['status'] == 7 || $memberA['source'] == 0){
					return ['code'=>2,'msg'=>'不可释放数据'];
				}
             	$this->where('id',$v)->update(['status' => 8,'create_uid'=>$uid]);
             }
             $this->commit();
             return ['code'=>1,'msg'=>'已释放'];
         }catch(Exception $e){
             $this->rollback();
             return ['code'=>0,'msg'=>'释放失败'.$e->getMessage()];
         }
	 }
    /**
     * 根据id条件 伪 删除的会员
     * @param $where
     */
    public function delMember($param)
    {
        $ids = json_decode($param);
        try{
            foreach($ids as $v){
                $this->where('id',$v)->update(['delete_status' => 2]);
            }
            $this->commit();
            return ['code'=>1,'msg'=>'删除成功'];
        }catch(Exception $e){
            $this->rollback();
            return ['code'=>0,'msg'=>'删除失败'.$e->getMessage()];
        }
    }
    /**
     * 根据会员的id 获取会员的信息和追踪信息
     * @param $id $where(时间段)
     */
    public function getOneMember($id)
    {
        $memberArr = $this->where('id', $id)->where($this->whereCansee())->find();
    		if(empty($memberArr)){
    			return ['code'=>0,'msg'=>'该客户已被移除'];
    		}
    		if ($memberArr['second_relation'] == 0) {
    			$Relation = $memberArr['first_relation'];
    			$memberArr['time'] = $memberArr['entry_time'];
    			$memberArr['relation_id'] = $memberArr['first_relation'];
    		}else {
    			$Relation = $memberArr['second_relation'];
    			$memberArr['time'] = $memberArr['second_time'];
    			$memberArr['relation_id'] = $memberArr['second_relation'];
    		}
        $userArr = Db::name('user')->where(['id'=>$Relation])->find();
        $memberArr['relation'] = $userArr['real_name'];

        $track = Db::name('track_member')->where(['m_id'=>$id])->where($this->whereCansee())->order('id desc')->select();
        if (!empty($track)){
            foreach($track as &$vo){
                $username = Db::name('user')->where(['id'=>$vo['u_id']])->value('real_name');
                $vo['username'] = $username;
                $vo['time'] = date('Y-m-d H:i:s',$vo['time']);
            }
        }
        $memberArr['track'] = $track;
        return $memberArr;
    }
    /**
     * 根据会员的id 修改会员的信息
     * @param $id
     */
    public function memberEdit($param)
    {
        try{
            $result = $this->save($param,['id' => $param['id']]);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{
                return msg(1, url('member/memberEdit',['id' => $param['id']]), '修改信息成功');
            }
        }catch(\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }

    /**
     * 根据时间段搜索相对应的追踪信息
     * @param $KL-time
     */
    public function getTrackList($where){
        $result = Db::name('track_member')->where($where)->select();
        foreach($result as &$vo){
            $username = Db::name('user')->where(['id'=>$vo['u_id']])->value('real_name');
            $vo['name'] = $this->where(['id'=>$where['m_id']])->value('name');
            $vo['username'] = $username;
            $vo['time'] = date('Y-m-d H:i:s',$vo['time']);
        }
        return $result;
    }
    /**
     * 根据跟踪的id 查看会员的信息
     * @param $id
     */
    public function getTrackMember ($id)
    {
        $trackArr = Db::name('track_member')->where(['id'=>$id])->find();
        $memberN = $this->where(['id'=>$trackArr['m_id']])->value('name');
        $username = Db::name('user')->where(['id'=>$trackArr['u_id']])->value('real_name');
        $trackArr['memberN'] = $memberN;
        $trackArr['username'] = $username;
        return $trackArr;
    }
    /**
     * 根据id条件删除的跟踪条件信息
     * @param $id
     */
    public function delTrack($id)
    {
        $id = (int)($id);
        try{
            Db::name('track_member')->where('id',$id)->delete();
            Db::name('track_member')->commit();
            return ['code'=>1,'msg'=>'删除成功'];
        }catch(\Exception $e){
            Db::name('track_member')->rollback();
            return ['code'=>0,'msg'=>'删除失败'.$e->getMessage()];
        }
    }
    /**
     * 根据添加跟踪信息
     * @param
    */
    public function addTrack($param)
    {
        try{
            $result = Db::name('track_member')->insert($param);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{
                return msg(1, url('member/memberEdit',['id' => $param['m_id']]).'#test=44', '加载成功');
            }
        }catch (\Exception $e){
            return msg(-2, '', $e->getMessage());
        }
    }
    /**
     * 根据条件分配会员到相应的用户
     * @param $where
     */
    public function insMember($param,$where)
    {
        $ids = json_decode($param);
        try{
            foreach($ids as $v){
                $this->where('id',$v)->update($where);
            }
            $this->commit();
            return ['code'=>1,'msg'=>'添加成功'];
        }catch(\Exception $e){
            $this->rollback();
            return ['code'=>0,'msg'=>'添加失败'.$e->getMessage()];
        }
    }

    /**
     * 客户回收站
     * 列表
     */
    public function trashMember ($where, $offset, $limit)
    {
        $tra_memArr = $this->where($where)->where($this->whereCansee())->limit($offset, $limit)->order('id desc')->select();
        foreach($tra_memArr as $vo){
            $firstRelation = $vo['first_relation'];
            $userArr = Db::name('user')->where(['id'=>$firstRelation])->find();
            $vo['first_relation'] = $userArr['real_name'];
            $vo['entry_time'] = date('Y-m-d',$vo['entry_time']);
        }
        return $tra_memArr;
    }
    /**
     * 根据id条件恢复的会员
     * @param $where
     */
    public function recoveryMem($param)
    {
        try{
            foreach($param as $v){
                $this->where('id',$v)->update(['delete_status' => 1]);
            }
            $this->commit();
            return ['code'=>1,'msg'=>'恢复成功'];
        }catch(Exception $e){
            $this->rollback();
            return ['code'=>0,'msg'=>'恢复失败'.$e->getMessage()];
        }
    }
    /**
     * 根据id条件删除的会员
     * @param $where
     */
    public function deleteMem($param)
    {
        try{
            foreach($param as $v){
                $this->where('id',$v)->delete();
            }
            $this->commit();
            return ['code'=>1,'msg'=>'删除成功'];
        }catch(Exception $e){
            $this->rollback();
            return ['code'=>0,'msg'=>'删除失败'.$e->getMessage()];
        }
    }
	/**
	 * 根据 @id 修改分享状态
	 */
	 public function shareStatus($id){
		 $uid = session('id');
		 try{
            $this->where(['id' => $id])->update(['share' => 1,'create_uid'=>$uid]);
             return ['code'=>1,'msg'=>'分享成功'];
         }catch(Exception $e){
             return ['code'=>0,'msg'=>'分享失败'.$e->getMessage()];
         }
	 }
	 /**
 	 * 取消分享状态
 	 */
	 public function cancelShare($id){
		 $uid = session('id');
		try{
			$this->where(['id' => $id])->update(['share' => 0,'create_uid'=>$uid]);
			 return ['code'=>1,'msg'=>'已取消'];
		 }catch(Exception $e){
			 return ['code'=>0,'msg'=>'数据错误'.$e->getMessage()];
		 }
	 }
	 /**
 	 * 根据 @id 修改分享/跟踪分配
 	 */
 	 public function ajaxShare($param,$data){
 		 try{
			 $memOne = $this->where(['id' => $param['mid']])->find();
			 if($memOne['share'] == 1){
				 $this->where(['id' => $param['mid']])->update($data);
	             return ['code'=>1,'msg'=>'分配成功'];
			 }else{
				 if($memOne['status'] == 8){
					 $this->where(['id' => $param['mid']])->update($data);
		             return ['code'=>1,'msg'=>'分配成功'];
				 }else{
					 return ['code'=>2,'msg'=>'不是释放客户'];
				 }
				 return ['code'=>2,'msg'=>'不是分享客户'];
			 }
          }catch(Exception $e){
              return ['code'=>0,'msg'=>'分配失败'.$e->getMessage()];
          }
 	 }
}
